package consul

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"log"
	"month5/common/nacos"
)

func Consul() {
	// 创建并初始化 Consul 客户端
	nac := nacos.Config
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", nac.Consul.Host, nac.Consul.Port) //地址
	consul, err := api.NewClient(config)
	if err != nil {
		log.Printf("初始化 Consul 客户端失败: %v", err)
		return
	}
	// 创建健康检查配置
	check := &api.AgentServiceCheck{
		Interval:                       "5s",
		Timeout:                        "5s",
		GRPC:                           fmt.Sprintf("%s:%d", nac.Grpc.Host, nac.Grpc.Port),
		DeregisterCriticalServiceAfter: "30s",
	}
	// 创建服务注册信息
	a := new(api.AgentServiceRegistration)
	a.ID = "1"
	a.Name = nac.Consul.Name
	a.Tags = []string{"GRPC"}
	a.Port = nac.Grpc.Port
	a.Address = nac.Grpc.Host
	a.Check = check

	// 服务注册函数

	// 注册服务到 Consul
	err = consul.Agent().ServiceRegister(a)
	if err != nil {
		return
	}
}
